import config from './config';
import {Lunar, Solar} from './lunar';
import { getBz } from "./api";

// 数量转万
export function numberFormatter(number, precision = 2) {
    if (typeof number !== 'number') {
        return '0';
    }
    // 超过一万的情况下将数量除以 10000 并保留指定的小数位数
		if (number > 10000) {
				const result = number / 10000;
				if (precision !== undefined) {
						return result.toFixed(precision) + 'w';
				} else {
						return result + 'w';
				}
		} else {
				// 不超过一万的情况下直接返回原始数量
				return number.toString();
		}
}
export function formatDate(time, type = 'date') {
	var date = new Date(time);
	var Y = date.getFullYear() + '年';
	var M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '月';
	var D = (date.getDate() < 10 ? '0' + (date.getDate()) : date.getDate()) + '日';
	var h = (date.getHours() < 10 ? '0' + (date.getHours()) : date.getHours()) + ':';
	var m = (date.getMinutes() < 10 ? '0' + (date.getMinutes()) : date.getMinutes()) + ':';
	var s = (date.getSeconds() < 10 ? '0' + (date.getSeconds()) : date.getSeconds());
	var strDate = '';
	if (type === 'date') {
		strDate = Y + M + D;
	} else if (type === 'datetime') {
		strDate = Y + M + D + h + m + s;
	}
	return strDate;
}
export function image(name,type = 'no'){
	if(name && (name.startsWith('http') || name.startsWith('https'))){
		return name;
	}
	if(type == 'no'){
		return config.imageUrl + name;
	}else if(type == 'yes'){
		return config.cesuUrl + '/' + name;
	}
}

/*
* 获取个人年月日, 获取阳历以及阴历
* 例如：
* 阳历：2024-11-19
* 阴历：二〇二四年十月十九
* date = new Date()
* */
export async function getCalendarDate(params = {}) {
	// 实例化
	// 阳历数据
	var solarExample = Solar.fromDate(new Date(params.date));
	// 阴历数据
	var lunarExample = Lunar.fromDate(new Date(params.date));
	console.log('年：'+lunarExample.getYearZhi() + ':' + lunarExample.getYearShengXiao()); // 农历年份
	console.log('月日：'+lunarExample.getMonthInChinese() + ':' + lunarExample.getDayInChinese()); // 农历月日
	console.log('时辰：'+lunarExample.getTimeZhi()); // 时辰
	// 阳历日期
	let solarYear = solarExample.getYear();
	let solarMonth = solarExample.getMonth().toString().padStart(2, '0');
	let solarDay = solarExample.getDay().toString().padStart(2, '0');
	let solarHour = solarExample.getHour().toString().padStart(2, '0');
	let solarMinute = solarExample.getMinute().toString().padStart(2, '0');
	let solarSecond = solarExample.getSecond().toString().padStart(2, '0');
	let solarDate = solarYear + '年' + solarMonth + '月' + solarDay + '日' + ' ' + solarHour.toString().padStart(2, '0') + ':' + solarMinute.toString().padStart(2, '0') + ':' + solarSecond.toString().padStart(2, '0');
	// 年龄
	let age = getAge(params.date);
	console.log("阳历节点")
	// 阴历日期
	let lunarYear = lunarExample.getYearZhi() + lunarExample.getYearShengXiao();
	let lunarMonth = lunarExample.getMonthInChinese() + '月';
	let lunarDay = lunarExample.getDayInChinese();
	let lunarHour = lunarExample.getTimeZhi() + '时';
	let lunarDate = lunarYear + lunarMonth + lunarDay + ' ' + lunarHour;
	let lunarDateChinese = lunarExample.toString();
	console.log("生效节点")
	let shengXiao = lunarExample.getYearShengXiao();

	// 十神数据
	let shiShen = getShiShen(lunarExample);
	// 天干数据
	let tianGan = getTianGan(lunarExample);
	// 地支数据
	let diZhi = getDiZhi(lunarExample);
	// 藏干数据
	let zangGan = getCangGan(lunarExample);
	console.log("十神数据--藏干数据")
	let aiZangGan = getAiZangGan(zangGan);
	// 地势数据
	let diShi = getDiShi(lunarExample);
	// 纳音数据
	let naYin = getNaYin(lunarExample);
	// 空亡数据
	let kongWang = getKongWang(lunarExample);
	// 节气数据
	let jieQi = getJieQi(lunarExample);
	console.log("地势数据--节气数据")
	// 起大运周岁数据
	let qiDayun = getQiDaYun(lunarExample);
	// 大运数据
	let daYun = getDaYun(lunarExample);
	// 流年数据
	// let liuNian = getLiuNian(solarYear, solarMonth, solarDay, solarHour, solarMinute, solarSecond);
	let liuNian = getLiuNian(lunarExample);
	// 获取司令
	let siLing = getSiLing();
	// 吉神凶煞
	let jiShenXiongSha = [];

	// 胎元, 命宫, 身宫
	let taiYuan = [];
	if(params.shenShaParams && Object.keys(params.shenShaParams).length > 0){
		params.shenShaParams.day = "2024-05-06 09:10:00";
		console.log("起大运周岁数据--吉神凶煞", params.shenShaParams.day.toString())
		let jiShenData = await getJiShenXiongSha(params.shenShaParams);
		let { jsList, tyList } = jiShenData;
		jiShenXiongSha = jsList;
		taiYuan = tyList;
	}
	console.log("胎元, 命宫, 身宫")
	// 构造返回对象
	const result = {
		// 阴历数据
		lunarYear,
		lunarMonth,
		lunarDay,
		lunarHour,
		lunarDate,
		lunarDateChinese,
		// 阳历数据
		solarYear,
		solarMonth,
		solarDay,
		solarHour,
		solarMinute,
		solarSecond,
		solarDate,
		shengXiao,
		age,
		// 十神数据
		shiShen,
		// 天干数据
		tianGan,
		// 地支数据
		diZhi,
		// 藏干数据
		zangGan,
		// 地势数据
		diShi,
		// 纳音数据
		naYin,
		// 空亡数据
		kongWang,
		// 节气数据
		jieQi,
		// 起大运周岁数据
		qiDayun,
		// 大运数据
		daYun,
		// 流年数据
		liuNian,
		// 获取司令
		siLing,
		// ai请求的藏干参数
		aiZangGan,
	};
	// 动态添加 `jiShenXiongSha` 属性
	if (params.shenShaParams && Object.keys(params.shenShaParams).length > 0) {
		result.jiShenXiongSha = jiShenXiongSha;
	}
	if (params.shenShaParams && taiYuan.length > 0) {
		result.taiYuan = taiYuan;
	}
	console.log("ttttttttttttttttt", result)
	return result;
	// // 转阴历
	// var lunar = solarExample.getLunar();
	//
	// console.log(lunar.toString());
	// console.log(lunar.toFullString());
}
// 获取十神
function getShiShen(lunarExample){
	let eightChar = lunarExample.getEightChar();
	let userinfo = uni.getStorageSync("userinfo") || "";
	let RiShishen = eightChar.getDayShiShenGan(); // 日柱十神,  根据性别判断,  男的为元男,女的为元女
	if (userinfo) {
		userinfo = JSON.parse(userinfo);
		RiShishen = userinfo.gender == "男" ? "元男" : "元女";
	}
	return [
		eightChar.getYearShiShenGan(),
		eightChar.getMonthShiShenGan(),
		RiShishen,
		eightChar.getTimeShiShenGan(),
	];
}

// 获取天干
function getTianGan(lunarExample){
	let eightChar = lunarExample.getEightChar();
	return [
		{
			title: eightChar.getYearGan(),
			type: eightChar.getYearWuXing().slice(0,1)
		},
		{
			title: eightChar.getMonthGan(),
			type: eightChar.getMonthWuXing().slice(0,1)
		},
		{
			title: eightChar.getDayGan(),
			type: eightChar.getDayWuXing().slice(0,1)
		},
		{
			title: eightChar.getTimeGan(),
			type: eightChar.getTimeWuXing().slice(0,1)
		}
	]
}
// 获取地支
function getDiZhi(lunarExample){
	let eightChar = lunarExample.getEightChar();
	return [
		{
			title: eightChar.getYearZhi(),
			type: eightChar.getYearWuXing().slice(1,2)
		},
		{
			title: eightChar.getMonthZhi(),
			type: eightChar.getMonthWuXing().slice(1,2)
		},
		{
			title: eightChar.getDayZhi(),
			type: eightChar.getDayWuXing().slice(1,2)
		},
		{
			title: eightChar.getTimeZhi(),
			type: eightChar.getTimeWuXing().slice(1,2)
		}
	]
}
// 获取藏干,  获取不到
function getCangGan(lunarExample){
	let eightChar = lunarExample.getEightChar();
	// 年藏干
	const yearHideGan = eightChar.getYearHideGan();
	const yearShiShenZhi = eightChar.getYearShiShenZhi();
	// 月藏干
	const monthHideGan = eightChar.getMonthHideGan();
	const monthShiShenZhi = eightChar.getMonthShiShenZhi();
	// 日藏干
	const dayHideGan = eightChar.getDayHideGan();
	const dayShiShenZhi = eightChar.getDayShiShenZhi();
	// 时藏干
	const timeHideGan = eightChar.getTimeHideGan();
	const timeShiShenZhi = eightChar.getTimeShiShenZhi();
	// 合并数据
	const mergedYear = yearHideGan.map((item, index) => item + (yearShiShenZhi[index] || ''));
	const mergedMonth = monthHideGan.map((item, index) => item + (monthShiShenZhi[index] || ''));
	const mergedDay = dayHideGan.map((item, index) => item + (dayShiShenZhi[index] || ''));
	const mergedTime = timeHideGan.map((item, index) => item + (timeShiShenZhi[index] || ''));
	return [
		mergedYear,
		mergedMonth,
		mergedDay,
		mergedTime
	]
}
// 获取地势
function getDiShi(lunarExample){
	let eightChar = lunarExample.getEightChar();
	return [
		eightChar.getYearDiShi(),
		eightChar.getMonthDiShi(),
		eightChar.getDayDiShi(),
		eightChar.getTimeDiShi()
	]
}
// 获取纳音
function getNaYin(lunarExample){
	let eightChar = lunarExample.getEightChar();
	return [
		eightChar.getYearNaYin(),
		eightChar.getMonthNaYin(),
		eightChar.getDayNaYin(),
		eightChar.getTimeNaYin()
	]
}
// 获取空亡
function getKongWang(lunarExample){
	let eightChar = lunarExample.getEightChar();
	return [
		eightChar.getYearXunKong(),
		eightChar.getMonthXunKong(),
		eightChar.getDayXunKong(),
		eightChar.getTimeXunKong()
	]
}
// 获取节气
function getJieQi(lunarExample){
	let prev = lunarExample.getPrevJieQi();
	let next = lunarExample.getNextJieQi();
	return {
		prevJieQi: prev.getName() + ' ' +prev.getSolar().toYmdHms(),
		nextJieQi: next.getName() + ' ' +next.getSolar().toYmdHms(),
	}
}
// 获取起大运周岁
function getQiDaYun(lunarExample){
	let eightChar = lunarExample.getEightChar();
	// 获取男运
	var yun = eightChar.getYun(2);
	return '出生' + yun.getStartYear() + '年' + yun.getStartMonth() + '个月' + yun.getStartDay() + '天后起运';
}

// 获取大运
function getDaYun(lunarExample){
	let eightChar = lunarExample.getEightChar();
	// 获取男运
	var yun = eightChar.getYun(2);
	// 获取大运表
	var daYunArr = yun.getDaYun();
	var list = [];
	for (var i=0, j=daYunArr.length; i<j; i++) {
		var daYun = daYunArr[i];
		list.push(daYun.getGanZhi());
	}
	list.shift();
	list.pop();
	return list;
}
// 获取流年
function getLiuNian(lunarExample) {
	let eightChar = lunarExample.getEightChar();
	// 获取男运
	var yun = eightChar.getYun(2);
	// 获取大运表
	var daYunArr = yun.getDaYun();

	var liuNianArr = daYunArr.map((item,index)=>{
		return item.getLiuNian().map((citem,cindex)=>{
			return {
				data:{
					[citem.getYear()]: citem.getGanZhi()
				},
				year: citem.getYear(),
				ganzhi: citem.getGanZhi()
			}
		});
	});
	liuNianArr.shift();
	liuNianArr.pop();
	// 所有流年数据展开“拍平”的数据
	let allData = liuNianArr
		.map(item => item.map(citem => citem.data))  // 提取 data
		.flat().reduce((acc, item) => {
			let year = Object.keys(item)[0]; // 获取每个对象的年份（键）
			acc[year] = [item[year]]; // 将年份作为键，值为对应的值
		return acc;
	}, {});
	// 获取起始年
	let firstYear = liuNianArr.map((item,index)=>{
		return item[0].year;
	})
	// 获取截至年
	let lastYear = liuNianArr.map((item) => {
		return item[item.length - 1]?.year; // 访问每个子数组的最后一个元素的 year 属性
	});
	return {
		firstYear,
		lastYear,
		liuNianArr,
		allData
	}
}

// 获取年龄
export function getAge(birthDateString){
	const targetDate = new Date();
	// 将字符串转换为 Date 对象
	const birth = new Date(birthDateString.replace(/-/g, '/')); // 替换 '-' 为 '/' 兼容 Date 解析
	const target = new Date(targetDate);

	let age = target.getFullYear() - birth.getFullYear();

	// 判断是否满周年生日
	if (
		target.getMonth() < birth.getMonth() ||
		(target.getMonth() === birth.getMonth() && target.getDate() < birth.getDate())
	) {
		age--;
	}

	return age;
}
// 获取司令
function getSiLing(){
	let userinfo = uni.getStorageSync('userinfo');
	let silingStr = "乾造";
	if (userinfo) {
		userinfo = JSON.parse(userinfo);
		silingStr = userinfo.gender == "男" ? "乾造" : "坤造";
	}
	return silingStr;
}
// 获取三方接口数据
function getJiShenXiongSha(data) {
	console.log("获取吉神凶煞", data);
	return getBz(data).then(res => {
		// 获取吉神凶煞
		let jsList = res.data.shenSha.map(item => {
			// 将字符串用空格拆分成数组并删除最后一个元素
			let parts = item.split(" ");
			parts.pop(); // 删除数组最后一个元素
			return parts;
		});
		// 获取胎元, 命宫, 身宫数据
		let tyList = [
			{
				title: "胎元",
				value: res.data.ty,
				valueSub: res.data.tyNy,
			},
			{
				title: "命宫",
				value: res.data.mg,
				valueSub: res.data.mgNy,
			},
			{
				title: "身宫",
				value: res.data.sg,
				valueSub: res.data.sgNy,
			}
		];
		// 返回处理后的列表
		return{
			jsList,
			tyList
		}
	});
}
// 获取ai藏干请求参数,  根据上面的藏干数据进行处理,传入上面的藏干数据
export function getAiZangGan(zangGan){
	return zangGan.map(item => item.map(citem => citem.slice(1)));
}



